package middleware

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	r := gin.Default()
	// 全局中间件
	r.Use(LogInput)
	// 使用 TokenCheck 中间件和其他处理程序
	r.GET("/protected", TokenCheck(), func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "Protected route accessed successfully",
		})
	})

	r.Run(":3013")
}

// LogInput 全局中间件
func LogInput(ctx *gin.Context) {
	requestBody, _ := ctx.GetRawData()
	ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
	mp := make(map[string]interface{})
	mp["request_url"] = ctx.Request.RequestURI
	mp["status"] = ctx.Writer.Status()
	mp["method"] = ctx.Request.Method
	mp["access_token"] = ctx.GetHeader("access_token")
	mp["body"] = string(requestBody)
	log.Panicln(mp)
	ctx.Next()
	fmt.Println("called log input")
}

// TokenCheck 中间件
func TokenCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		accessToken := c.GetHeader("access_token")
		expectedToken := "your_expected_token" // 从环境变量或其他安全存储中获取

		if accessToken != expectedToken {
			c.JSON(http.StatusUnauthorized, gin.H{
				"message": "Token validation failed",
			})
			c.Abort()
			return
		}

		c.Set("user_name", "ni")
		c.Set("user_id", "100")
		c.Next()
	}
}
